package bylw.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;

// 分页工具类
public class HibernatePageModel implements Serializable {
	private static final long serialVersionUID = 1L;
	private Integer pageNo;// 当前页
	private Integer upPage;// 上一页
	private Integer downPage;// 下一页
	private Integer totalPage;// 总页数
	private Integer totalData;// 总数据数
	private Integer pageSize;// 每页显示多少条
	@SuppressWarnings("unchecked")
	private List list;// 要显示的list

	public Integer getPageNo() {
		return pageNo;
	}

	public void setPageNo(Integer pageNo) {
		this.pageNo = pageNo;
	}

	public Integer getUpPage() {
		return upPage;
	}

	public void setUpPage(Integer upPage) {
		this.upPage = upPage;
	}

	public Integer getDownPage() {
		return downPage;
	}

	public void setDownPage(Integer downPage) {
		this.downPage = downPage;
	}

	public Integer getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(Integer totalPage) {
		this.totalPage = totalPage;
	}

	public Integer getTotalData() {
		return totalData;
	}

	public void setTotalData(Integer totalData) {
		this.totalData = totalData;
	}

	public Integer getPageSize() {
		return pageSize;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	@SuppressWarnings("unchecked")
	public List getList() {
		return list;
	}

	@SuppressWarnings("unchecked")
	public void setList(List list) {
		this.list = list;
	}

	@SuppressWarnings("unchecked")
	public static HibernatePageModel query(String hql, Session session,
			Integer pageNo, Integer pageSize) {
		if (pageNo <= 0) {
			pageNo = 1;
		}
		HibernatePageModel pm = new HibernatePageModel();
		Long dataCount = (Long) session.createQuery("select count(*) " + hql)
				.uniqueResult();
		Integer totalData = dataCount.intValue();
		int totalPage = 0;
		if (totalData % pageSize == 0) {
			totalPage = totalData / pageSize;
		} else if (totalData % pageSize >= 0) {
			totalPage = totalData / pageSize + 1;
		}
		if (pageNo > totalPage) {
			pageNo = totalPage;
			pm.setPageNo(totalPage);
		} else {
			pm.setPageNo(pageNo);
		}
		List list = new ArrayList();
		if (totalData > 0) {
			list = session.createQuery(hql).setFirstResult(
					pageSize * (pageNo - 1)).setMaxResults(pageSize).list();
		}
		if (pageNo == 1) {
			pm.setUpPage(1);
		} else {
			pm.setUpPage(pageNo - 1);
		}
		if (pageNo == totalPage) {
			pm.setDownPage(totalPage);
		} else {
			pm.setDownPage(pageNo + 1);
		}
		pm.setList(list);
		pm.setTotalData(dataCount.intValue());
		pm.setTotalPage(totalPage);
		pm.setPageSize(pageSize);
		return pm;
	}

}